﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Globalization;

namespace SimpleReminder
{
    public class EventWeekly : EventBase
    {
        public EventWeekly(DataRow dr)
            : base(dr)
        {
            if (base.Type != MyEvents.EventTypes.Weekly)
                throw new MyEvents.InvalidEventTypeException();
        }

        bool[] _weeklyDay = new bool[7];

        public override void From(DataRow dr)
        {
            base.From(dr);

            _weeklyDay[0] = (bool) dr[MyEvents.COL_WEEKLYDAY_SUN];
            _weeklyDay[1] = (bool)dr[MyEvents.COL_WEEKLYDAY_MON];
            _weeklyDay[2] = (bool)dr[MyEvents.COL_WEEKLYDAY_TUE];
            _weeklyDay[3] = (bool)dr[MyEvents.COL_WEEKLYDAY_WED];
            _weeklyDay[4] = (bool)dr[MyEvents.COL_WEEKLYDAY_THU];
            _weeklyDay[5] = (bool)dr[MyEvents.COL_WEEKLYDAY_FRI];
            _weeklyDay[6] = (bool)dr[MyEvents.COL_WEEKLYDAY_SAT];
        }

        public override bool IsTimeToRun()
        {
            DateTime now = DateTime.Now;
            int thisWeekNo = Utils.GetWeekNo(now);
            int lastWeekNo = Utils.GetWeekNo(base.LastRunTime);

            if (base.CanRun && 
                _weeklyDay[(int) now.DayOfWeek] && 
                (Math.Abs(thisWeekNo - lastWeekNo) >= Frequence || thisWeekNo == lastWeekNo) && 
                (now - base.LastRunTime).TotalHours >= 1 && 
                StartDate.Hour == now.Hour && 
                StartDate.Minute == now.Minute 
                )
            {
                return true;
            }
            return false;
        }

    }
}
